import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './index.less';
import moment from 'moment';
import ExportOrder from './exportOrder';
import ReportForm from '../orderList/reportForm';
import {
    Card,
    DatePicker,
    Input,
    Select,
    Checkbox,
    Form,
    Button,
    message,
    Spin,
    Modal,
    List,
    Row,
    Col,
    Icon,
    Table ,
    Avatar,
    Popover,
    Menu,
    Tooltip,
    Tag
  } from 'antd';
import HeaderTab from '@/components/HeaderTab';
import DeliverModal from './deliverModal.js';
import BatchDeliverModal from './batchDeliverModal';
import ExpressBillModal from './expressBillModal';
import ChangeRemark from '../orderList/changeRemark';
import ModifyModal from './modifyModal';
import {abs} from '@/utils/utils';
//import templateURL from './template';

const confirm = Modal.confirm;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option,OptGroup  } = Select;


function unitConversion() {
  /**
   * 获取DPI
   * @returns {Array}
   */
  this.conversion_getDPI =function () {
      var arrDPI = new Array;
      if (window.screen.deviceXDPI) {
          arrDPI[0] = window.screen.deviceXDPI;
          arrDPI[1] = window.screen.deviceYDPI;
      } else {
          var tmpNode = document.createElement("DIV");
          tmpNode.style.cssText = "width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
          document.body.appendChild(tmpNode);
          arrDPI[0] = parseInt(tmpNode.offsetWidth);
          arrDPI[1] = parseInt(tmpNode.offsetHeight);
          tmpNode.parentNode.removeChild(tmpNode);
      }
      return arrDPI;
  };
  /**
   * px转换为mm
   * @param value
   * @returns {number}
   */
  this.pxConversionMm = function (value) {
      var inch = value/this.conversion_getDPI()[0];
      var c_value = inch * 25.4;
//      console.log(c_value);
      return c_value;
  };
  /**
   * mm转换为px
   * @param value
   * @returns {number}
   */
  this.mmConversionPx = function (value) {
      var inch = value/25.4;
      var c_value = inch*this.conversion_getDPI()[0];
//      console.log(c_value);
      return c_value;
  }
}

function createDocument(order) {
  let document = {};
  document.documentID =  order.Id;
  document.contents = [];
  document.contents.push(createCustomerTemplete(order));
  return document;
}

function createCustomerTemplete(order) {
  var customerTemplete = {};
  customerTemplete.templateURL = `https://adminstore-local.xiaokeduo.com/static/tem.json?${Math.random()}`;
  customerTemplete.data = order;
  return customerTemplete;
}

function getUUID(len, radix) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  var uuid = [], i;
  radix = radix || chars.length;
  if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
  } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
              r = 0 | Math.random() * 16;
              uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
          }
      }
  }
  return uuid.join('');
}

const PrintSelectModal = ({printList,_this}) => {
  //const { printList } = props;
  const onChange = (val) => {
    //console.log(val)
    _this.setState({
      defaultPrinter:val
    })
  };
  const handleOk = () => {
    let {state:{defaultPrinter}} = _this;
    if(!defaultPrinter) return message.error('请选择打印机');
    _this.getExpressList();
    _this.getAddressList();
    _this.getList({pageSize:10000})
    _this.handleExpressBillModalVisible(true);
    _this.showPrintListModal(false)
  };
  const onCancel = () => {
    _this.showPrintListModal(false)
  }
  return (
    <Modal
      title='选择打印机'
      visible={true}
      onOk={handleOk}
      onCancel={onCancel}
    >
      <Select style={{width:'100%'}} onChange={onChange}>
      {
        printList&&printList.map((v,index)=>{
          return <Option key={index} value={v.name}>{v.name}</Option>
        })
      }
      </Select>
    </Modal>
  );
}


@Form.create()
class Index extends Component {
  state = {
    indeterminate:false,
    expandForm: false,
    modalVisible:false,
    batchModalVisible:false,
    expressBillModalVisible:false,
    printListModalVisible:false,
    exportLoading: false,
    searchLoading:false,
    defaultPrinter:'',
    printList:[],
    printExpressBillList:[],
    list:[],
    orderItem:[],
    formValues:{},
    checkedList:[],
    formData: {},
    paginationProps: {
      showSizeChanger: true,
      showQuickJumper: false,
      showTotal: total => `共 ${total} 条记录`,
      pageSize: 10,
      total: 0,
      current: 1,
    },
    tabs: [
      {
        title: '发货管理',
        key: `/${window.storeId}/order/delivery`,
        // disabled: true
      },
      {
        title: '批量发货',
        key: `/${window.storeId}/order/delivery/batch`,
      },
    ],
    loadFinished:false,
    deliverInfo:{}
  }

  componentDidMount(){
    window.Isoption = true;
    const {match} =this.props;
    if(match&&match.params&&match.params.id){
      this.props.form.setFieldsValue({
        OrderNo:match.params.id
      })
      this.requestList({OrderNo:match.params.id});
    }else{
      this.requestList();
    }
  }
  componentWillMount() {
    window.Isoption = false;
  }

  requestList = (params) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'deliverManage/GetOrderList',
      payload: {
        PageIndex: params && params.current ? params.current : 1,
        PageSize: params && params.pageSize ? params.pageSize : 10,
        MinDate: params && params.MinDate ? params.MinDate : null,
        MaxDate: params && params.MaxDate ? params.MaxDate : null,
        PaymentChannel: params && params.PaymentChannel ? params.PaymentChannel : 0,
        MemberName: params && params.MemberName ? params.MemberName : '',
        OrderNo: params && params.OrderNo ? params.OrderNo : '',
        RightsStatus: params && params.RightsStatus ? params.RightsStatus : 0,
        Receiver: params && params.Receiver ? params.Receiver : '',
        GoodsKeyWord: params && params.GoodsKeyWord ? params.GoodsKeyWord : '',
        OrderStatus: params && params.OrderStatus ? params.OrderStatus : 2,
        PrintStatus: params && params.PrintStatus ? params.PrintStatus : 0,
        // SortName: params && params.SortName ? params.SortName : 'Id',
        Sort: params && params.Sort !=undefined ? params.Sort : 1,  //降序
      },
      callback:{
        success:(data)=>{
          const {paginationProps}=this.state;
          paginationProps.current=params &&params.current?params.current:1;
          paginationProps.pageSize=params &&params.pageSize?params.pageSize:10;
          paginationProps.total=data.Data.Total;
          this.setState({
            list:data.Data.DataList||[],
            loadFinished:true,
            searchLoading:false,
            paginationProps,
            checkedList:[],
            indeterminate: false,
            checkAll:false
          })
        }
      }
    });
  }

  // 获取物流公司列表
  getExpressList = () => {
    const { dispatch } = this.props;
    dispatch({
      type:'deliverManage/GetStoreExpressList',
    })
  }

  // 获取发货地址列表
  getAddressList = () => {
    const { dispatch,form:{setFieldsValue}} = this.props;
    dispatch({
      type:'deliverManage/GetSendAddrList',
      callback:{
        success:(data)=>{
          
          // setFieldsValue({
          //   storeAddressId:data.Data&&data.Data.DataList&&data.Data.DataList.length&&data.Data.DataList[0]?data.Data.DataList[0].Id:''
          // })
        }
      }
    })
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    //this.requestList();
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  clickexportOrder =() => {
    const { dispatch, form} = this.props;
    form.validateFields((err, values) => {
        if(values.Date) {
            const datas = {
                ...values,
                MaxDate:values.Date && values.Date[1]?moment(values.Date[1]).format('YYYY-MM-DD'):'',
                MinDate:values.Date && values.Date[0]?moment(values.Date[0]).format('YYYY-MM-DD'):'',
            };
            this.setState({
                formData: datas,
                exportLoading: true,
            })
            dispatch({
                type: 'orderList/GetTaskName',
                payload: {
                    TaskType: 0
                },
                callBack: {
                    success: res => {
                        if(res.Code===0) {
                            this.setState({
                                data: res.Data,
                                visible: true,
                                exportLoading: false,
                            })
                        }
                    },
                    error: res=> {
                        message.error(res.Msg)
                    }
                }
            })
        }
        else {
            message.error('请选择起始时间')
        }
    })
  }

  // 点击查看
clickReportForm =() => {
    const title="已生成报表";
    const TaskType = 0; //类型
    const width = 640;
    this.reportForm.show({width, title, TaskType})
}

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      cardList,
      allTagList,
      loading,
    } = this.props;
    const {exportLoading,searchLoading} = this.state;
    return (
      <Form  layout="inline">
        <Row >
          <Col span={8}>
            <FormItem label="下单时间">
              {getFieldDecorator('Date')(<RangePicker style={{ width: '100%' }} placeholder={['开始日期', '    结束日期']} />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="买家信息">
              {getFieldDecorator('MemberName')(
                <Input className="xkd-width-per-100" placeholder="昵称/手机号"/>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="订单号">
              {getFieldDecorator('OrderNo')(<Input style={{ width: '100%' }} placeholder="订单号"/>)}
            </FormItem>
          </Col>
        </Row>
        <Row >
          <Col span={8}>
            <FormItem label="支付方式">
              {getFieldDecorator('PaymentChannel',{
                initialValue:0
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value={0}>全部</Option>
                  <Option value={1}>微信支付</Option>
                  <Option value={2}>货到付款</Option>
                  <Option value={3}>线下支付</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="收货人">
              {getFieldDecorator('Receiver')(
                <Input style={{ width: '100%' }} placeholder="姓名/电话"/>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="商品信息">
              {getFieldDecorator('GoodsKeyWord')(<Input style={{ width: '100%' }} placeholder="商品名称/商品编码"/>)}
            </FormItem>
          </Col>
        </Row>
        <Row >
          <Col span={8}>
            <FormItem label="维权状态">
              {getFieldDecorator('RightsStatus',{
                initialValue:0
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value={0}>全部</Option>
                  <Option value={1}>无</Option>
                  <Option value={2}>退款中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="打印状态">
              {getFieldDecorator('PrintStatus',{
                initialValue:0
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value={0}>全部</Option>
                  <OptGroup label="快递单">
                    <Option value={1}>已打印快递单</Option>
                    <Option value={2}>未打印快递单</Option>
                  </OptGroup>
                  <OptGroup label="发货单">
                    <Option value={3}>已打印发货单</Option>
                    <Option value={4}>未打印发货单</Option>
                  </OptGroup>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="发货状态">
              {getFieldDecorator('OrderStatus',{
                initialValue:2
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value={2}>待发货</Option>
                  <Option value={3}>已发货</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div className="screenNavButton">
            <Button type="primary" onClick={this.handleSearch} loading={searchLoading}>
              筛选
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.clickexportOrder} loading={exportLoading}>
              批量导出
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.clickReportForm}>
              查看已生成报表
            </Button>
          </div>
        </div>
      </Form>
    );
  }

  renderForm() {
    // const { expandForm } = this.state;
    // return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    return this.renderAdvancedForm()
  }

  onCheckboxChange = (e,id) => {
    const {checkedList,list} = this.state;
    let checked=e.target.checked;
    //console.log(e,id)
    if(list.length){
      let index=list.findIndex(item=>item.Id==id);
      if(!checked&&index>-1){
        list[index].checked=false;
      }else if(checked&&index>-1){
        list[index].checked=true;
      }
      let index2 = checkedList.findIndex(item=>item==id);
      checked?checkedList.push(id):index2>-1?checkedList.splice(index2,1):'';
      //console.log(index,id,checkedList)
      this.setState({
        list,
        checkedList,
        indeterminate: !!checkedList.length && (checkedList.length < list.length),
        checkAll: checkedList.length === list.length,
      });
    }
  }

  onCheckAllChange = (e) => {
    const {checkedList,list} = this.state;
    let arr=[];
    let checked=e.target.checked;
    checked?list.forEach(item=>{
      item.checked=true;
      arr.push(item.Id)
    }):list.forEach(item=>{
      item.checked=false;
      arr=[];
    })
    this.setState({
      checkedList: arr,
      indeterminate: false,
      checkAll: checked,
    });
  }

  handleSearch = () => {
    const {dispatch,form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        MinDate:
          fieldsValue.Date && fieldsValue.Date[0]
            ? moment(fieldsValue.Date[0]).format('YYYY-MM-DD')
            : '',
        MaxDate:
          fieldsValue.Date && fieldsValue.Date[1]
            ? moment(fieldsValue.Date[1]).format('YYYY-MM-DD')
            : '',
      };
     // console.log(values)
      this.setState({
        formValues: values,
        searchLoading:true
      });
      // console.log(values);
       this.requestList({ ...values });
    });
  }

  // 单个发货弹框
  handleModalVisible = (flag) => {
    this.setState({
      modalVisible: !!flag
    })
  }

  showDeliverModal = (id) => {
    const {dispatch} = this.props;
    const { list } = this.state;
    let index = list.findIndex((item)=>item.Id==id);
    if(index>-1){
      this.setState({
        orderItem: list[index],
      },()=>{
        this.getExpressList();
        this.getAddressList();
         dispatch({
            type:'deliverManage/GetPrintedCourierBill',
            payload:{OrderId:id},
            callback:{
              success:()=>{

              }
            }
          })
        this.handleModalVisible(true);
      });
    }
  }

  comfirm = (params) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'deliverManage/Delivery',
      payload: {
        orderId: params.orderId,
        orderNo: params.orderNo,
        storeAddressId:params.storeAddressId,
        expressId:params.expressId,
        waybillNumber:params.waybillNumber,
        listItemId:params.listItemId,
        listNum:params.listNum,
      },
      callback:{
        success:(data)=>{
          this.handleModalVisible();
          this.setState({
            checkedList:[],
            indeterminate: false,
          })
          this.requestList();
          message.success('发货成功')
        },
        error:(data)=>{
          message.error(data.Msg)
        }
      }
    });
  }

  // 批量发货弹框
  handleBatchModalVisible = (flag) => {
    this.setState({
      batchModalVisible: !!flag
    })
  }

  showBatchDeliverModal = () => {
    // const { list } = this.state;
    // let index = list.findIndex((item)=>item.Id==id);
    // if(index>-1){
    //   this.setState({
    //     orderItem: list[index],
    //   },()=>{
    //     this.getAddressList();
    //     this.handleBatchModalVisible(true);
    //   });
    // }
    const { checkedList }  = this.state;
    if(!checkedList.length) return message.error('至少选择一个订单');
    this.getPendingDeliverList();
    this.getExpressList();
    this.getAddressList();
    this.handleBatchModalVisible(true);
  }

  // 获取待发货列表信息
  getPendingDeliverList = () => {
    const { dispatch } = this.props;
    const { checkedList }  = this.state;
    let ids=checkedList.join(',');
    dispatch({
      type:'deliverManage/GetOrderDeliverList',
      payload:{
        OrderIds:ids
      }
    })
  }

  BatchComfirm = (params,callback) => {
    const {dispatch} = this.props;
    dispatch({
      type: 'deliverManage/DeliveryBatch',
      payload: params,
      callback:{
        success:(data)=>{
          this.handleBatchModalVisible();
          this.setState({
            checkedList:[],
            indeterminate: false,
          })
          if(callback&&typeof callback === 'function'){
            callback()
          }else{
            this.requestList();
            message.success('发货成功')
          }
        },
        error:(data)=>{
          message.error(data.Msg)
        }
      }
    });
  }

  // 连接socket
  doConnect =  (callback) => {
    this.socket={};
    let that=this;
    if ('WebSocket' in window) {
        this.socket = new WebSocket("ws://127.0.0.1:13528");
    }
    else {
        alert('当前浏览器不支持websocket');
        return false;
    }

    this.socket.onopen = function (event) {
        console.log("Websocket准备就绪,连接到客户端成功");
        if(typeof callback === 'function' ) callback()
    };

    // 监听消息
    this.socket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        if ("getPrinters" == data.cmd) {
            //打印机列表
            var printerList = data.printers;
            that.setState({
              printList:data.printers
            })
            if (data.defaultPrinter != undefined && data.defaultPrinter != null && data.defaultPrinter != "") {
                this.defaultPrinter = data.defaultPrinter;
            }
            // createPrintList(printerList);
        }
        else if ("notifyPrintResult" == data.cmd) {
            // if(data.errorCode==18){

            // }
            const { expressBillModalVisible,formValues } = that.state;
            let arr = data.printStatus.filter(v=>v.status==='success');
            if(data.printStatus.length===arr.length){
             // console.log(that.expressBillModal,data,876)
              that.expressBillModal.setState({
                printLoading:false
              })
              if(!expressBillModalVisible){
                message.success('操作成功')
                that.PrintedCourierBill();
                that.requestList({...formValues});
              }
              that.setState({
                expressBillModalVisible:false,
                checkedList:[],
                checkAll:false,
                indeterminate:false
              })
            }else{
              message.error('操作失败')
              that.expressBillModal.setState({
                printLoading:false
              })
            }

        }
        else {
            console.log("返回数据:" + JSON.stringify(data));
        }
    };

    // 监听Socket的关闭
    this.socket.onclose = function (event) {
        console.log('关闭socket', event);
    };

    this.socket.onerror = function (event) {
        that.showCainiaoConfirm()
    };
    return true;
  }

  // 打印快递单
  showCainiaoConfirm =  ()=> {
    let title=(
      <span>您尚未安装菜鸟插件，<a href="http://cloudprint-docs-resource.oss-cn-shanghai.aliyuncs.com/download.html" target="_blank">请下载</a></span>
    );
    confirm({
      title: title,
      content: '安装成功后需重新打开浏览器',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        console.log('OK');
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  // 打印快递单
  handleExpressBillModalVisible = (flag) => {
    this.setState({
      expressBillModalVisible: !!flag
    })
    // if(!!!flag){
    //   this.setState({
    //     printExpressBillList:[]
    //   })
    // }
  }

  showExpressBillModal = () => {
    const { checkedList,list}  = this.state;
    const {dispatch} = this.props;
    this.doConnect(()=>{
      if(!checkedList.length) return message.error('至少选择一个订单');     
      if(checkedList.length){
        let arr=[];
        checkedList.forEach(item=>{
            let index=list.findIndex(v=>v.Id==item);
            index>-1?arr.push(list[index]):'';
        })
        this.setState({
          printExpressBillList:arr
        })   
        if(checkedList.length==1){
          dispatch({
            type:'deliverManage/GetPrintedCourierBill',
            payload:{OrderId:checkedList[0]},
            callback:{
              success:()=>{

              }
            }
          })
        }     
      }
      var request = {
            requestID: getUUID(10, 10),
            version: "1.0",
            cmd: "getPrinters"
        };
      this.socket.send(JSON.stringify(request));
      this.showPrintListModal(true)
      //this.handleExpressBillModalVisible(true);
    })
  }

  transformData = (obj) => {
    let Data= JSON.parse(JSON.stringify(obj));
    let data=JSON.parse(JSON.stringify(Data.expressBillInfo));
    data.coordinates.forEach(v=>{
         if(v.fontWeightTagChecked){
             v.fontWeightTagChecked=800;
         }else{
             v.fontWeightTagChecked=600;
         }
         if(v.id==1){
             v.text=Data.sendInfo.ContractName;
         }else  if(v.id==2){
             v.text=Data.sendInfo.Name;
         }else  if(v.id==3){
             v.text=Data.sendInfo.ContractPhone;
         }else  if(v.id==4){
             v.text=Data.ReceivingName;
         }else  if(v.id==5){
             v.text=Data.ReceivingTelephone;
         }else  if(v.id==6){
             v.text=Data.ZipeCode;
         }else  if(v.Id==7){
             v.text=Data.receivingAddress;
         }else  if(v.id==8){
             v.text=Data.ReceivingCity;
         }else  if(v.id==9){
             v.text=Data.OrderNo;
         }else  if(v.id==11){
             v.text=Data.Remark;
         }else  if(v.id==12){
             v.text=Data.MemberRemark;
         }else  if(v.id==13){
             v.text=Data.oemInfo.storeName;
         }else  if(v.id==14){
             v.text=Data.printDate;
         }
       })

       return data;
  }

  ExpressBillComfirm = (params,type) => {  
        if(params){
          this.setState({
            deliverInfo:params
          })
        }      
        if(type){
          params.ItemList.forEach((item,index)=>{
            //console.log(item,445)
            item.expressBillInfo=this.transformData(item);
         })
        }else{
          params.ItemList.forEach((item,index)=>{
           // console.log(item,445)
            item.expressBillInfo=this.transformData(item);
         })
        }
        var task = {};
        task.taskID = getUUID(8, 10);
        task.preview = false;
        task.previewType = "pdf";
        task.printer = this.state.defaultPrinter||"Microsoft Print to PDF";
        task.notifyMode = "allInOne";
        //task.firstDocumentNumber = 10;
        //task.totalDocumentCount = 100;
        task.documents = [];
        if(type){
          params.ItemList.forEach( ( element,index) => {
            var document = createDocument(element);
            task.documents.push(document);
        });
        }else{
          params.ItemList.forEach( ( element,index) => {
            var document = createDocument(element);
            task.documents.push(document);
        });
        }

        var printData = {};
        printData.cmd = "print";
        printData.requestID = getUUID(10, 10);
        printData.version = "1.0";
        printData.task = task;
        console.log(params)
       if(type){
         this.BatchComfirm({
          storeAddressId:params.storeAddressId,
          ItemList:params.items
         },()=>{
          this.socket.send(JSON.stringify(printData));
         })
       }else{        
        this.socket.send(JSON.stringify(printData));
       }      
  }

  // 标记为已打印快递单
  PrintedCourierBill = () => {
    const{ dispatch } = this.props;
    const { checkedList,printExpressBillList,deliverInfo } = this.state;
    //console.log(checkedList,printExpressBillList,7878787)
    let arr=[],expressIdList=[],waybillNumberList=[];
    printExpressBillList.forEach(v=>{
      arr.push(v.Id);
    })
    deliverInfo.items.forEach(v=>{
      expressIdList.push(v.ExpressId)
      waybillNumberList.push(v.WaybillNumber)
    })
    dispatch({
      type:'deliverManage/PrintedCourierBill',
      payload:{
        OrderIdList:arr,
        StoreAddressId:deliverInfo.storeAddressId,
        ExpressIdList:expressIdList,
        WaybillNumberList:waybillNumberList
      }
    })
  }

   // 头部状态切换
   onTabChange = id => {
    this.setState(
      {
        activeId: id,
      },
      () => {
        router.replace({
          pathname: `${id}`,
        });
      }
    );
  };

  onChange = (page) => {
    this.requestList({current:page})
  }

  onShowSizeChange= (page,pageSize) => {
    this.requestList({pageSize:pageSize,current:1})
  }

  //表头筛选
  onTableChange = (pagination, filters, sorter) => {
    const {formData} = this.state;
    if(sorter.order ==='descend') {
        formData.Sort ='Desc';
    } else {
        formData.Sort ='Asc';
    }
    this.setState({
        formData,
    })
    this.requestList({Sort:sorter.order==="ascend"?0:1})
  }

  handleMenuClick = (e) =>{
    console.log(e);
    let key=e.key;
    switch(key){
      case "1":
      const { checkedList }  = this.state;
        let ids=checkedList.join(',');
        window.open(`/#/${window.storeId}/order/delivery/print/${ids}`);
        break;
      case "2":
        window.open(`/#/${window.storeId}/order/delivery/print`);
        break;
      default:
        break;
    }
  }

  printInvoice = () => {
    const { checkedList }  = this.state;
    if(!checkedList.length) return message.error('至少选择一个订单');
    let ids=checkedList.join(',');
    window.open(`/#/${window.storeId}/order/delivery/print/${ids}`);
  }

  printSmallBill = () =>{
    const { checkedList }  = this.state;
    if(!checkedList.length) return message.error('至少选择一个订单');
    let ids=checkedList.join(',');
    window.open(`/#/${window.storeId}/order/localdelivery/print/${ids}`);
  }

   // 刷新页面
   clickrefrech = () => {
    const {formValues} = this.state;
    // this.setState({
    //     loading: true
    // }, () => {
      this.requestList();
    // })
    // this.forceUpdate();
}

lookDetail = (OrderNo) => {
  window.open(`/#/${window.storeId}/order/details/${OrderNo}`);
}

  // 获取快递单模板列表数据
  getList = (param) => {
    const { dispatch } = this.props;
    dispatch({
        type:'expressBill/GetList',
        param:{
            PageSize:param&&param.pageSize?param.pageSize:10,
            PageIndex:param&&param.pageIndex?param.pageIndex:1
        },
        callback:{
            success:()=>{
                this.setState({
                    loaded:false
                })
            }
        }
    })
}

showPrintListModal = (flag) => {
    this.setState({
      printListModalVisible:!!flag
    })
}

// 根据id获取模板信息
getInfo = (id,callback) => {
  const { dispatch,form:{setFieldsValue} } = this.props;
  dispatch({
      type:'expressBill/GetInfo',
      param:{
          Id:id
      },
      callback:{
          success:(data)=>{
              if(callback&&typeof callback === 'function'){
                let jsonData={};
                let obj={};
                if(data.Data.JsonData&&typeof data.Data.JsonData === 'string'){
                  jsonData=JSON.parse(data.Data.JsonData);
                }
                obj.coordinates=jsonData.coordinates||[];
                obj.TemplateHeight=data.Data.TemplateHeight;
                obj.TemplateWidth=data.Data.TemplateWidth;
                obj.coordinates.forEach(v=>{
                  v.x_mm=new unitConversion().pxConversionMm(v.x);
                  v.y_mm=new unitConversion().pxConversionMm(v.y);
                  v.width_mm=new unitConversion().pxConversionMm(v.width);
                  v.height_mm=new unitConversion().pxConversionMm(v.height);
                  v.fontSize_mm= new unitConversion().pxConversionMm(v.fontSize);
                })
                callback(obj)
              }
          }
      }
  })
}

showModifyModal = (OrderNo) => {
  this.modifyModal.showModal(OrderNo)
}

  render() {
    const columns = [
        {
          title: '商品信息',
          dataIndex: 'NickName',
          width:'20.8%'
        },
        {
          title: '单价/数量',
          dataIndex: 'Telephone',
          align: 'right',
          width: '12.5%',
        },
        {
          title: '售后',
          dataIndex: 'LastBuyTime',
          width: '8.3%',
        },
        {
          title: '实付金额',
          dataIndex: 'TotalPoints',
          width: '12.5%',
          align: 'right',
          //sorter: true,
        },
        {
          title: '收货人',
          dataIndex: 'TotalFee',
          width: '12.5%',
         // sorter: true,
        },
        {
          title: '买家信息',
          dataIndex: 'TotalFeeNum',
          width: '12%',
         // sorter: true,
        },
        {
          title: '下单时间',
          dataIndex: 'SingleFee',
          width: '12%',
          sorter: true,
        },
        {
          title: '操作',
         // width: '10%',
          align: 'right',
        },
      ];
    const formItemLayout = {
      labelCol: {
        xs: { span: 2 },
        sm: { span: 2 },
        md: { span: 2 },

      },
      wrapperCol: {
        xs: { span: 22 },
        sm: { span: 22 },
        md: { span: 22 },
      },
    };
    const {
      getFieldDecorator, getFieldsError, getFieldError, isFieldTouched, getFieldValue
    } = this.props.form;
    const { list, paginationProps,indeterminate,checkAll,modalVisible,batchModalVisible,expressBillModalVisible,printListModalVisible,orderItem,tabs,loadFinished,checkedList, formData,printExpressBillList,printList} = this.state;
    const { confirmLoading,batchConfirmLoading, loading, loadList,cdnUrl,form,pendingDeliverList,expressList,sendAddrList,expressBillList,expressBillListLoading,expressListLoading ,addressListLoading,allLoading,oemInfo,expressBillInfo,PrintedCourierBillList} = this.props;

    const listItem= (item,index) =>{
      const iamgeVel  = item.OrderTag ===0 ?6: item.OrderTag;
      let orderIndex=list.findIndex(val=>val.Id==item.Id);

     return (
      <List.Item className={styles.listBody}>
          <Row className={styles.navtebalRow}>
              <Col span={18} className={styles.orderNo}>
                  <Checkbox onChange={(e)=>this.onCheckboxChange(e,item.Id)} checked={item.checked}>订单号：{item.OrderNo}</Checkbox>
                    <span className="xkd-ml16">{item.DeliveryTypeName +' / '+item.PaymentChannelNameStr}</span>
                    <span className="xkd-ml16">
                      {
                        item.PrintedCourierBill?<Tag>快递单已打印</Tag>:null
                      }
                      {
                        item.PrintedInvoice?<Tag>发货单已打印</Tag>:null
                      }
                    </span>
              </Col>
              <Col span={6}>
                  <div style={{textAlign: 'right', paddingRight: 16}}>
                      {
                        item.Remark?
                        <Popover title="买家留言" content={item.Remark?item.Remark:'无'}>
                            <span>
                                <img
                                    src={cdnUrl + '/' + 'xkdnewyun/systemfile/store/icon/orderlist-wx.png' +'?x-oss-process=style/240'}
                                    width={16}
                                    height={16}
                                />
                            </span>
                        </Popover>:null
                      }
                      <span className="xkd-ml16" onClick={
                          () => {
                              const title="修改备注";
                              const OrderNo = item.OrderNo;
                              this.changeRemark.show({title, OrderNo}, this.clickrefrech)
                          }
                      }>
                        {item.MerchantRemark?(<Tooltip title={item.MerchantRemark}>
                             <img
                                src={cdnUrl + '/' + `xkdnewyun/systemfile/store/icon/orderlist-remark0${iamgeVel}.png` +'?x-oss-process=style/240'}
                                width={16}
                                height={16}
                             />
                            </Tooltip>):(
                                 <img
                                 src={cdnUrl + '/' + `xkdnewyun/systemfile/store/icon/orderlist-remark0${iamgeVel}.png` +'?x-oss-process=style/240'}
                                 width={16}
                                 height={16}
                              />
                        )}
                      </span>
                  </div>
              </Col>
          </Row>
          <Row className={styles.navRowItem} style={{height: `${item.OrderItem.length * 96}px`}}>
              <Col span={10}>
                  <List
                      dataSource={item.OrderItem ?item.OrderItem:[]}
                      renderItem={(data, index) => {
                          return (
                              <Row className={item.OrderItem.length === index+ 1 ?styles.leftItemNoborder : styles.leftItem}>
                                  <Col span={19}>
                                      <List.Item key={data.Id} className={styles.listItem}>
                                          <List.Item.Meta
                                              avatar={<Avatar src={cdnUrl + '/' + data.ThumbnailUrl +'?x-oss-process=style/240'} />}
                                              title={
                                                  <span title={data.ProductName} style={{maxWidth:145,height:40}}>
                                                      {data.ProductName}
                                                  </span>
                                              }
                                              description={
                                                  <span
                                                      title={data.SkuName}
                                                      className="xkd-text-ellipsis"
                                                  >{data.SkuName}</span>
                                              }
                                          />
                                            <div>
                                                  <div>{'￥' +abs(data.SingleFee,2)}</div>
                                                  <div>{'x'+ data.BuyNum}</div>
                                              </div>
                                      </List.Item>
                                  </Col>
                                  <Col span={5}>{data.RightsStatusName}</Col>
                              </Row>
                          )
                      }}
                  >
                  </List>
              </Col>
              <Col span={3}>
                <div className="xkd-text-right" >
                    <div className={styles.price}>￥{abs(item.OrderPayAmount,2)}</div>
                    <div className={`${styles.freightColor} xkd-font12`}>(含运费￥{abs(item.OrderPayFreightAmount,2)})</div>
                    <div className={`${styles.freightColor} xkd-font12`}>{item.PaymentChannelNameStr}</div>
                </div>
              </Col>
              <Col span={3}>
                <div >
                    <div>{item.ReceivingName}</div>
                    <div>{item.ReceivingTelephone}</div>
                </div>
              </Col>
              <Col span={3}>
                <div >
                    <div>{item.MemberName}</div>
                    <div>{item.MemberTelephone}</div>
                </div>
              </Col>
              <Col span={3} >
                  <span>{item.CreateTime}</span>
              </Col>
              <Col span={2} style={{textAlign: 'right'}}>
                <div className="xkd-text-right" index={orderIndex}>
                    {
                      item.OrderStatusName==='待发货'?item.IsPartialDeliver?<Button type="primary" size="small" onClick={()=>this.showDeliverModal(item.Id)}>继续发货</Button>
                      :<Button type="primary" size="small" onClick={()=>this.showDeliverModal(item.Id)} style={{width:72}}>发货</Button>:(
                        <Button type="primary" size="small" onClick={()=>this.showModifyModal(item.OrderNo)} style={{width:72}}>修改物流</Button>
                      )
                    }
                    <Button size="small" style={{marginTop:8,}} onClick={()=>this.lookDetail(item.OrderNo)}>查看详情</Button>
                </div>
              </Col>
          </Row>
      </List.Item>
     );
    }
     const menu1 = (
        <Menu onClick={this.handleMenuClick}>
          <Menu.Item key={1} disabled={!checkedList.length}><Icon type="printer" />打印选中的订单</Menu.Item>
          <Menu.Item key={2} ><Icon type="printer" />打印筛选出来的{checkedList.length}个订单</Menu.Item>
        </Menu>
      );
      const menu2 = (
        <Menu onClick={this.handleMenuClick}>
          <Menu.Item key="1" disabled={!checkedList.length}><Icon type="printer" />打印选中的订单</Menu.Item>
          <Menu.Item key="2" ><Icon type="printer" />打印筛选出来的{checkedList.length}个订单</Menu.Item>
        </Menu>
      );
      const menu3 = (
        <Menu onClick={this.handleMenuClick}>
          <Menu.Item key="1" disabled={!checkedList.length}><Icon type="printer" />打印选中的订单</Menu.Item>
          <Menu.Item key="2" ><Icon type="printer" />打印筛选出来的{checkedList.length}个订单</Menu.Item>
        </Menu>
      );
      const menu4 = (
        <Menu onClick={this.handleMenuClick}>
          <Menu.Item key="1" disabled={!checkedList.length}><Icon type="global" />对选中的订单发货</Menu.Item>
          <Menu.Item key="2"><Icon type="global" />对筛选出来的{checkedList.length}个订单发货</Menu.Item>
          <Menu.Item key="3"><Icon type="global" />对已打印快递单的订单发货</Menu.Item>
        </Menu>
      );

    return (
      <Fragment>
        {/* <HeaderTab
          _this={this}
          type="slider"
          activeId={this.state.activeId}
          onChange={this.onTabChange}
          tabs={tabs}
        >

        </HeaderTab> */}
        <Spin spinning={!loadFinished}>
        <Card
        bordered={false}
            className={styles.deliverManage}
        >
            <div style={{background:'#fafafa',marginBottom:16,paddingTop:16,paddingRight:16,boxSizing:'border-box'}}>
                <div className="tableListForm">{this.renderForm()}</div>
            </div>
            <div style={{paddingLeft:16}}>
                <Checkbox
                  indeterminate={indeterminate}
                  onChange={this.onCheckAllChange}
                  checked={checkAll}
                >
                  当页全选
                </Checkbox>
                {/*<Dropdown overlay={menu1} trigger={["click"]}>
                    <Button style={{ marginLeft: 8 }}>
                        打印发货单 <Icon type="down" />
                    </Button>
                </Dropdown>
                <Dropdown overlay={menu2} trigger={["click"]}>
                    <Button style={{ marginLeft: 8 }}>
                        打印快递单 <Icon type="down" />
                    </Button>
                </Dropdown>
                <Dropdown overlay={menu3} trigger={["click"]}>
                    <Button style={{ marginLeft: 8 }}>
                        打印电子面单 <Icon type="down" />
                    </Button>
                </Dropdown>
                <Dropdown overlay={menu4} trigger={["click"]}>
                    <Button style={{ marginLeft: 8 }}>
                        批量发货 <Icon type="down" />
                    </Button>
                </Dropdown>*/}
                <Button style={{ marginLeft: 8 }} onClick={this.printInvoice}>
                    打印发货单
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.printSmallBill}>
                    打印小票
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.showExpressBillModal}>
                    打印快递单
                </Button>
               {/* <Button style={{ marginLeft: 8 }}>
                    打印电子面单
                </Button> */}
                <Button style={{ marginLeft: 8 }} onClick={this.showBatchDeliverModal}>
                    批量发货
                </Button>
            </div>
            <List
                header={
                    <div>
                         <Table
                            //loading={loading}
                            //rowKey={record => record.Id}
                            dataSource={null}
                            columns={columns}
                            // rowSelection={rowSelection}
                            onChange={this.onTableChange}
                           // pagination={paginationProps}
                        />
                    </div>
                }
               // bordered={true}
               itemLayout="vertical"
                dataSource={list}
                pagination={{...paginationProps,onChange:this.onChange,onShowSizeChange:this.onShowSizeChange}}
                renderItem={item => listItem(item)}
                loading={loading}
            />
        </Card>
        {
          modalVisible?
           <DeliverModal
              form={form}
              modalVisible={modalVisible}
              addressList={sendAddrList}
              handleModalVisible={this.handleModalVisible}
              list={orderItem}
              comfirm={this.comfirm}
              expressList={expressList}
              confirmLoading={confirmLoading}
              addressListLoading={addressListLoading}
              expressListLoading={expressListLoading}
              allLoading={allLoading}
              PrintedCourierBillList={PrintedCourierBillList}
            /> :null
        }
        {
          batchModalVisible?
            <BatchDeliverModal
              form={form}
              modalVisible={batchModalVisible}
              addressList={sendAddrList}
              handleModalVisible={this.handleBatchModalVisible}
              list={pendingDeliverList}
              comfirm={this.BatchComfirm}
              expressList={expressList}
              confirmLoading={batchConfirmLoading}
              addressListLoading={addressListLoading}
              expressListLoading={expressListLoading}
              allLoading={allLoading}
            />:null
        }
        {
          expressBillModalVisible?
            <ExpressBillModal
              form={form}
              modalVisible={expressBillModalVisible}
              addressList={sendAddrList}
              expressBillList={expressBillList}
              handleModalVisible={this.handleExpressBillModalVisible}
              getInfo={this.getInfo}
              expressBillInfo={expressBillInfo}
              list={printExpressBillList}
              oemInfo={oemInfo}
              comfirm={this.ExpressBillComfirm}
              expressList={expressList}
              confirmLoading={batchConfirmLoading}
              addressListLoading={addressListLoading}
              expressListLoading={expressListLoading}
              expressBillListLoading={expressBillListLoading}
              onRef={ref=>this.expressBillModal=ref}
              PrintedCourierBillList={PrintedCourierBillList}
            />:null
        }
        {
          printListModalVisible?
          <PrintSelectModal
            printList={printList}
            _this={this}
          />:null
        }
        <ModifyModal onRef={e=>this.modifyModal=e}/>
        <ChangeRemark
                ref ={e => {
                    this.changeRemark = e;
                }}
        />
        <ExportOrder _this = {this} visible={this.state.visible} data={formData} />
        <ReportForm
                ref={e => {
                    this.reportForm = e;
                }}
            />
        </Spin>
      </Fragment>
    )
  }
}
export default connect(({ deliverManage, global, loading,expressBill }) => ({
  cdnUrl:global.oemInfo.cdnUrl,
  oemInfo:global.oemInfo,
  expressList:deliverManage.expressList,
  sendAddrList:deliverManage.sendAddrList,
  pendingDeliverList:deliverManage.pendingDeliverList,
  loading: loading.effects['deliverManage/GetOrderList'],
  confirmLoading: loading.effects['deliverManage/Delivery'],
  batchConfirmLoading: loading.effects['deliverManage/DeliveryBatch'],
  addressListLoading: loading.effects['deliverManage/GetSendAddrList'],
  expressListLoading: loading.effects['deliverManage/GetStoreExpressList'],
  expressBillListLoading: loading.effects['expressBill/GetList'],
  allLoading:loading.global,
  expressBillList: expressBill.expressBillList,
  expressBillInfo:expressBill.expressBillInfo,
  PrintedCourierBillList:deliverManage.PrintedCourierBillList
}))(Index);
